<?php

namespace App\Service\Admin;

use App\Constants\Rbac\AdminCode;
use App\Model\Admin\AdminModel;
use App\Model\Rbac\RoleModel;
use App\Service\BaseService;
use App\Service\Rbac\RbacService;
use App\Utils\Helper;
use App\Utils\SecretUtil;
use Hyperf\Collection\Arr;
use Hyperf\Di\Annotation\Inject;

class AdminService extends BaseService
{

    #[Inject]
    protected AdminModel $adminModel;

    #[Inject]
    protected RoleModel $roleModel;

    // 账号是否有路由权限
    public function adminHasAccessRoute(array $adminInfo, $routeId)
    {
        if ($adminInfo['is_root'] == AdminCode::IS_ROOT) {
            return true;
        }
        if (empty($adminInfo['role_ids'])) {
            return false;
        }
        return \Hyperf\Support\make(RbacService::class)->anyRoleHasRoute($adminInfo['role_ids'], $routeId);
    }

    // 获取账号的权限
    public function getManagerRoutes($adminInfo)
    {
        $routes = [];
        if ($adminInfo['is_root'] == AdminCode::IS_ROOT) {
            $routes = \Hyperf\Support\make(RbacService::class)->getAllRoutes([], [
                'id',
                'pid',
                'type',
                'name',
                'path',
                'path',
            ]);
        } else {
            $routes = \Hyperf\Support\make(RbacService::class)->getRouteOfSomeRole($adminInfo['role_ids']);
        }
        return [
            'routes' => $routes,
            'tree' => Helper::generateTree($routes),
        ];
    }

    public function adminBaseInfo($adminId)
    {
        return $this->adminModel->findById($adminId, [
            'id',
            'nickname',
            'account',
            'login_pwd',
            'is_root',
            'role_ids',
        ])?->toArray();
    }

    // 添加管理员账号
    public function addAdmin($params, $actAdmin = null)
    {
        if ($params['is_root'] == AdminCode::IS_ROOT && $actAdmin) {
            if ($actAdmin['is_root'] != AdminCode::IS_ROOT) {
                return [false, '只有超级管理员能添加超级管理员账号'];
            }
        }
        $accEx = $this->adminModel->findByAcc($params['account'], ['id']);
        if ($accEx) {
            return [false, '账号已存在'];
        }
        $params['login_pwd'] = SecretUtil::encrypt($params['login_pwd']);
        if (empty($params['role_ids'])) {
            $params['role_ids'] = [];
        }
        $r = $this->adminModel->addOne($params);
        if ($r) {
            return [true, '创建成功'];
        }
        return [false, '创建失败'];
    }

    /**
     * @param $adminId
     * @param $params
     * @param array|null $handleBy 进行操作的管理员
     * @return array
     */
    public function updateAdminBase($adminId, $params, $handleBy = [])
    {
        $admin = $this->adminModel->findById($adminId);
        if (!$admin) {
            return [false, '账号不存在'];
        }
        // 修改账号级别
        if (!empty($params['is_root'])) {
            if ($admin->is_root != $params['is_root']) {
                if ($handleBy['is_root'] != AdminCode::IS_ROOT) {
                    return [false, '账号级别只有超级管理员能修改'];
                }
            }
        } else {
            unset($params['is_root']);
        }
        $r = $this->adminModel->updateById($adminId, $params);
        if ($r) {
            return [true, '更新成功'];
        }
        return [false, '没有改动'];
    }

    // 更新登录密码
    public function updateAdminLoginPwd($adminId, $newPwd)
    {
        if (!$newPwd) {
            return [false, '登录密码不能为空'];
        }
        $admin = $this->adminModel->findById($adminId);
        if (!$admin) {
            return [false, '账号不存在'];
        }
        $hashPwd = SecretUtil::encrypt($newPwd);
        $r = $this->adminModel->updateLoginPwd($adminId, $hashPwd);
        if ($r) {
            return [true, '更新成功'];
        }
        return [false, '更新失败'];
    }


    // 超级管理员权限修改
    public function updateAdminRoot($adminId, $isRoot)
    {
        $admin = $this->adminModel->findById($adminId);
        if (!$admin) {
            return [false, '账号不存在'];
        }
        $isRoot = intval($isRoot);
        if ($admin->is_root == $isRoot) {
            return [false, '没有改动'];
        }
        $r = $this->adminModel->updateIsRoot($adminId, $isRoot);
        if ($r) {
            return [true, '修改成功'];
        }
        return [false, '修改失败'];
    }


    // 账号列表
    public function managerPageList(array $params = [], $page = 1, $ps = 10)
    {
        $lists = $this->adminModel->pageListForAdmin($params, $page, $ps)->toArray();
        if (empty($lists['data'])) {
            return $lists;
        }
        $roleIds = [];
        foreach ($lists['data'] as $list) {
            if (!empty($list['role_ids'])) {
                $roleIds = array_merge($roleIds, $list['role_ids']);
            }
        }
        $roleArr = $this->roleModel->getSomeByIdsIdxId($roleIds, ['id', 'name',]);
        foreach ($lists['data'] as &$list) {
            $list['role_arr'] = Arr::only($roleArr, $list['role_ids']);
        }
        return $lists;
    }

    // 删除账号
    public function delAdmin($adminIds)
    {
        $arr = $this->adminModel->getSomeByIds($adminIds, ['id']);
        if ($arr->isEmpty()) {
            return [false, '数据为空'];
        }
        $r = $this->adminModel->delByIds($adminIds);
        if ($r) {
            return [true, '删除成功'];
        }
        return [false, '删除失败'];
    }
}